const app = getApp()
let qCloud = require("../../index.js");

Page({
    /** 页面的初始数据 */
    data: {
        imgPath: qCloud.config.STATIC_IMAGE_PATH,
        totalTask: 0, // 生产任务数
        totalNumber: 0, // 生产总数
        totalPrice: 0, // 生产总价
        completedTask: 0, // 已完成任务数
        completedNumber: 0, // 已完成总数
        completedPrice: 0, // 已完成总价
        completedTodayTask: 0, // 今日完成任务数
        completedTodayNumber: 0, // 今日完成总数
        completedTodayPrice: 0, // 今日完成总价
        operateProduceTaskId: 0, // 操作的生产任务ID
        popupBoxMark: 0, // 弹出框标记: 0-不显示; 1-完成; 2-删除; 3-继续生产;
        tabIndex: 1, // 页签坐标: 1-生产中; 2-已完成; 3-生产日报表;
        produceTaskList: [], // 生产任务列表

        btn0: false,
        btn1: false,
        btn2: false,
        btn3: false,
        btn4: false,
        btn5: false,
        btn6: false,
        btn7: false,
        btn8: false,
        btn9: false,

    },

    // 操作按钮的点击事件
    buttonTap(e) {
        let self = this;
        let index = e.currentTarget.dataset.index;
        let produceTask = self.data.produceTaskList[index];

        let operateProduceTaskId = 0; // 操作的生产任务ID
        let popupBoxMark = 0; // 弹出框标记: 0-不显示; 1-完成; 2-删除; 3-继续生产;
        let type = e.currentTarget.dataset.type; // 1-上数; 2-入库; 3-完成; 4-删除; 5-继续生产; 6-修改;
        if (type == "1") {
            // 跳转上数页面
            wx.navigateTo({
                url: "/pages/produce/upcount?produceTaskId=" + produceTask.produceTaskId,
            });
        } else if (type == "2") {
            // 跳转入库页面
            wx.navigateTo({
                url: "/pages/produce/taskin?produceTaskId=" + produceTask.produceTaskId,
            });
        } else if (type == "3") {
            operateProduceTaskId = produceTask.produceTaskId;
            popupBoxMark = 1;
        } else if (type == "4") {
            operateProduceTaskId = produceTask.produceTaskId;
            popupBoxMark = 2;
        } else if (type == "5") {
            operateProduceTaskId = produceTask.produceTaskId;
            popupBoxMark = 3;
        } else if (type == "6") {
            // 跳转修改页面
            wx.navigateTo({
                url: "/pages/produce/modify?produceTaskId=" + produceTask.produceTaskId,
            });
        }

        self.setData({
            operateProduceTaskId: operateProduceTaskId,
            popupBoxMark: popupBoxMark
        });
    },

    // 操作按钮(确认)
    operateButton() {
        let self = this;

        let url = "";
        let params = {
            produceTaskId: self.data.operateProduceTaskId
        };
        let msg = "";

        let popupBoxMark = self.data.popupBoxMark;
        if (popupBoxMark == "2") {
            url = qCloud.api.producetask_deleteProduceTask;
            msg = "删除生产任务";
        } else {
            url = qCloud.api.producetask_submitProduceTask;

            if (popupBoxMark == "1") {
                params.operateMark = "4";
                msg = "完成生产任务";
            } else if (popupBoxMark == "3") {
                params.operateMark = "3";
                msg = "继续生产任务";
            }
        }
        app.fetchApis(self, url, params, "POST", function (e) {
            let result = e.data;
            if (result.code == 200) {
                wx.showToast({
                    title: result.msg,
                    icon: "success"
                });

                // 查询生产任务列表
                self.queryProduceTaskList();
            }
        });

        self.closePopupBox();
    },

    // 关闭弹出框
    closePopupBox() {
        let self = this;
        self.setData({
            operateProduceTaskId: 0,
            popupBoxMark: 0
        });
    },

    // 跳转-新增生产任务页面
    addProduceTask() {
        wx.navigateTo({
            url: "/pages/produce/adds",
        });
    },

    // 顶部菜单选择
    tabClick(e) {
        let self = this;
        let tabIndex = e.currentTarget.dataset.index;
        self.setData({
            tabIndex: tabIndex // 页签坐标: 1-生产中; 2-已完成; 3-生产日报表;
        });
        if (tabIndex == 1 || tabIndex == 2) {
            self.queryProduceTaskList();
        } else {
            // TODO Joe 生产日报表
            self.setData({
                produceTaskList: []
            });
        }
    },

    // 跳转-生产任务详情页面
    todetailTap(e) {
        let self = this;
        let produceTaskList = self.data.produceTaskList;
        let index = e.currentTarget.dataset.index;
        let produceTask = produceTaskList[index];
        wx.navigateTo({
            url: "/pages/produce/details?produceTaskId=" + produceTask.produceTaskId,
        });
    },

    // 开始触摸,重置所有左滑内容
    touchstart: function (e) {
        let self = this;
        self.data.produceTaskList.forEach(function (item, idx) {
            // 只操作为true的
            if (item.isTouchMove) {
                item.isTouchMove = false;
            }
        });
        self.setData({
            startX: e.changedTouches[0].clientX,
            startY: e.changedTouches[0].clientY,
            produceTaskList: self.data.produceTaskList
        });
    },

    // 滑动事件
    touchEvent(e) {
        let self = this; // 防止this指向问题
        let index = e.currentTarget.dataset.index; // 当前下标
        let startX = self.data.startX; // 开始X坐标
        let startY = self.data.startY; // 开始Y坐标
        let touchMoveX = e.changedTouches[0].clientX; // 滑动变化x坐标
        let touchMoveY = e.changedTouches[0].clientY; // 滑动变化y坐标
        // 获取滑动角度
        let angle = self.angle({
            X: startX,
            Y: startY
        }, {
            X: touchMoveX,
            Y: touchMoveY
        });

        self.data.produceTaskList.forEach(function (item, idx) {
            item.isTouchMove = false;
            // 滑动超过30度，函数返回指定数字 x 的绝对值
            if (Math.abs(angle) > 30) return;
            if (idx == index) {
                if (touchMoveX > startX) // 右滑
                    item.isTouchMove = false;
                else // 左滑
                    item.isTouchMove = true;
            }
        });

        // 更新数据
        self.setData({
            produceTaskList: self.data.produceTaskList
        })
    },

    // 计算滑动角度，start 起点坐标，end 终点坐标
    angle: function (start, end) {
        let _X = end.X - start.X;
        let _Y = end.Y - start.Y;
        // 返回角度 Math.atan()函数返回一个数值的反正切（以弧度为单位）
        return 180 * Math.atan(_Y / _X) / (2 * Math.PI);
    },

    /** 生命周期函数--监听页面加载 */
    onLoad: function (options) {
        this.getUserInfo();
        this.getPermission();

        this.queryProduceTaskStatistic();
        this.queryProduceTaskList();

        this.setData({
            popupBoxMark: 0, // 弹出框标记: 0-不显示; 1-完成; 2-继续生产; 3-删除;
            tabIndex: 1 // 页签坐标: 1-生产中; 2-已完成; 3-生产日报表;
        });


    },

    /** 查询生产任务统计 */
    queryProduceTaskStatistic: function () {
        let self = this;
        let params = {};
        app.fetchApis(self, qCloud.api.producetask_queryProduceTaskStatistic, params, "POST", function (e) {
            let result = e.data;
            if (result.code == 200) {
                let data = result.data;
                self.setData({
                    totalTask: data.totalTask, // 生产任务数
                    totalNumber: data.totalNumber, // 生产总数
                    totalPrice: data.totalPrice, // 生产总价
                    completedTask: data.completedTask, // 已完成任务数
                    completedNumber: data.completedNumber, // 已完成总数
                    completedPrice: data.completedPrice, // 已完成总价
                    completedTodayTask: data.completedTodayTask, // 今日完成任务数
                    completedTodayNumber: data.completedTodayNumber, // 今日完成总数
                    completedTodayPrice: data.completedTodayPrice // 今日完成总价
                });
            }
        });
    },

    /** 查询生产任务列表 */
    queryProduceTaskList: function () {
        let self = this;
        let params = {
            type: self.data.tabIndex // 类型:1-生产中;2-已完成;查询待上报的任务列表时默认送1-生产中
        }
        app.fetchApis(self, qCloud.api.producetask_queryProduceTaskList, params, "POST", function (e) {
            let result = e.data;
            if (result.code == 200) {
                let data = result.data;

                let produceTaskList = [];
                for (let i = 0; i < data.produceTaskList.length; i++) {
                    let produceTaskInfo = data.produceTaskList[i];
                    let produceTask = {
                        produceTaskId: produceTaskInfo.produceTaskId, // 生产任务ID
                        produceTaskCode: produceTaskInfo.produceTaskCode, // 生产任务编号
                        produceTaskBedNo: produceTaskInfo.produceTaskBedNo, // 生产任务床号
                        produceTaskName: produceTaskInfo.produceTaskName, // 生产任务名称
                        produceTotal: produceTaskInfo.produceTotal, // 生产数量
                        completedPercentage: produceTaskInfo.completedPercentage, // 完成百分比
                        startTime: produceTaskInfo.startTime, // 开始时间
                        deliveryTime: produceTaskInfo.deliveryTime, // 交货时间
                        isTouchMove: false,
                        imageUrl: produceTaskInfo.imageId == "" ? self.data.imgPath + 'logo.png' : produceTaskInfo.imageUrl
                    };

                    produceTaskList.push(produceTask);
                }

                self.setData({
                    produceTaskList: produceTaskList
                });
            }
        });
    },

    /** 生命周期函数--监听页面卸载 */
    onUnload: function () {
        wx.switchTab({
            url: "/pages/index/index",
        });
    },

    /** 页面相关事件处理函数--监听用户下拉动作 */
    onPullDownRefresh: function () {
        this.getUserInfo();
        this.getPermission();

        this.queryProduceTaskStatistic();
        this.queryProduceTaskList();

        this.setData({
            popupBoxMark: 0, // 弹出框标记: 0-不显示; 1-完成; 2-继续生产; 3-删除;
            tabIndex: 1 // 页签坐标: 1-生产中; 2-已完成; 3-生产日报表;
        });
    },

    getUserInfo: function () {
        let self = this;
        app.fetchApis(self, qCloud.api.getInfo, {}, "GET", function (e) {
            if (e.data.code == 200) {
                qCloud.session.setPermi(e.data.permissions);
                qCloud.session.setRole(e.data.role);
                qCloud.session.setUser(e.data.user);
            }
        });
    },

    getPermission: function () {
        let self = this;
        let permission = qCloud.session.getPermi();
        if (permission && permission.length > 0) {
            if (permission.indexOf("apc:produce:add") != -1) {
                self.setData({
                    btn0: true
                });
            } else {
                self.setData({
                    btn0: false
                });
            }
            if (permission.indexOf("apc:produce:report") != -1) {
                self.setData({
                    btn1: true
                });
            } else {
                self.setData({
                    btn1: false
                });
            }
            if (permission.indexOf("apc:produce:warehousing") != -1) {
                self.setData({
                    btn2: true
                });
            } else {
                self.setData({
                    btn2: false
                });
            }
            if (permission.indexOf("apc:produce:complete") != -1) {
                self.setData({
                    btn3: true
                });
            } else {
                self.setData({
                    btn3: false
                });
            }
            if (permission.indexOf("apc:produce:edit") != -1) {
                self.setData({
                    btn4: true
                });
            } else {
                self.setData({
                    btn4: false
                });
            }
            if (permission.indexOf("apc:produce:remove") != -1) {
                self.setData({
                    btn5: true
                });
            } else {
                self.setData({
                    btn5: false
                });
            }
        } else {
            self.setData({
                btn0: false,
                btn1: false,
                btn2: false,
                btn3: false,
                btn4: false,
                btn5: false,
                btn6: false,
                btn7: false,
                btn8: false,
                btn9: false,
            })
        }
    }
});
